var SerialPort = require("serialport");
//Opening a Port


// module.exports = serial => {

let serialPort = new SerialPort("COM2", {
    //波特率，可在设备管理器中对应端口的属性中查看
    baudRate: 9600,
    autoOpen: false,
    dataBits: 8, //数据位
    parity: 'none', //奇偶校验
    stopBits: 1, //停止位
    flowControl: false
});
console.log("serialPort:", serialPort.path);
//连接串口后进行写入指令操作
serialPort.open(function(err) {
    console.log("IsOpen:", serialPort.isOpen);
    console.log("err:", err);
});
//指令监听
serialPort.on("data", function(data) {
    console.log("串口", serialPort.path, "收到字符串数据: " + data);
    let hex16 = Bytes2HexString(data);
    console.log("串口", serialPort.path, '收到16进制数据：', hex16);
});

const Bytes2HexString = (b) => {
    //获取十六进制数据
    let hexs = "";
    for (let i = 0; i < b.length; i++) {
        let hex = b[i].toString(16);
        if (hex.length === 1) {
            hexs = "0" + hex;
        }
        hexs += hex.toUpperCase();
    }
    return hexs;
};
//错误监听

serialPort.on("error", function(error) {
    console.log("error: " + error);
});

//获取端口列表
SerialPort.list(function(error, ports) {
    ports.forEach(function(port) {
        console.log(port.comName);
        console.log(port.pnpId);
        console.log(port.manufacturer);
    });
    console.log("当前存在在串口端口有：", ports);
});

// }